package org.zasadnyy.redlions.players.client.ui;

import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import org.zasadnyy.redlions.players.client.ds.PlayerRecord;
import org.zasadnyy.redlions.players.client.ds.PlayersDataSource;
import org.zasadnyy.redlions.players.client.util.SimpleDateFormat;
import org.zasadnyy.redlions.players.client.util.UkDateLocale;
import org.zasadnyy.redlions.players.shared.model.PlayerItem;
import org.zasadnyy.redlions.players.shared.model.TournamentItem;

import com.smartgwt.client.data.Criteria;
import com.smartgwt.client.data.Record;
import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.types.AnimationAcceleration;
import com.smartgwt.client.types.AnimationEffect;
import com.smartgwt.client.types.BkgndRepeat;
import com.smartgwt.client.types.Overflow;
import com.smartgwt.client.types.Positioning;
import com.smartgwt.client.types.VerticalAlignment;
import com.smartgwt.client.types.VisibilityMode;
import com.smartgwt.client.widgets.Img;
import com.smartgwt.client.widgets.Label;
import com.smartgwt.client.widgets.events.ClickEvent;
import com.smartgwt.client.widgets.events.ClickHandler;
import com.smartgwt.client.widgets.events.MouseOutEvent;
import com.smartgwt.client.widgets.events.MouseOutHandler;
import com.smartgwt.client.widgets.events.MouseOverEvent;
import com.smartgwt.client.widgets.events.MouseOverHandler;
import com.smartgwt.client.widgets.layout.HLayout;
import com.smartgwt.client.widgets.layout.SectionStack;
import com.smartgwt.client.widgets.layout.SectionStackSection;
import com.smartgwt.client.widgets.layout.VLayout;
import com.smartgwt.client.widgets.viewer.DetailFormatter;
import com.smartgwt.client.widgets.viewer.DetailViewer;
import com.smartgwt.client.widgets.viewer.DetailViewerField;

public class PlayerInfoLayout extends HLayout {

	private static final String NO_TOURNAMENTS_YET = "Турнірів немає, поки що ...";

	private PlayersDataSource datasource;

	private Img photo;
	private Label nameSurname;
	private DetailViewer generalDetailViewer;
	private DetailViewer tournamentsDetailViewer;

	public PlayerInfoLayout(PlayersDataSource datasource) {
		super();
		this.datasource = datasource;
		initLayout();
	}

	public void setPlayer(PlayerRecord record) {
		setFieldsData(record);
		markForRedraw();
	}

	private void setFieldsData(PlayerRecord record) {
		photo.setSrc("photos/" + record.getAttribute(PlayerItem.PHOTO_URL));

		nameSurname.setContents(record.getAttribute(PlayerItem.NAME) + " "
				+ record.getAttribute(PlayerItem.SURNAME));

		setCriteriaAndFetchData(generalDetailViewer, record);

		setCriteriaAndFetchData(tournamentsDetailViewer, record);
		setTournamentFields(tournamentsDetailViewer, record);
	}

	private void initLayout() {

		setMembersMargin(0);
		setHeight(PlayerCanvas.APP_HEIGHT);
		setWidth(PlayerCanvas.APP_WIDTH);
		setAnimateMembers(true);
		setAnimateHideAcceleration(AnimationAcceleration.SMOOTH_END);
		setAnimateShowAcceleration(AnimationAcceleration.SMOOTH_END);
		setAnimateShowEffect(AnimationEffect.FLY);

		VLayout leftPanel = new VLayout(0);
		leftPanel.setHeight100();
		leftPanel.setWidth("40%");
		addMember(leftPanel);

		final Img closeImg = createCloseFormImg();
		leftPanel.addChild(closeImg);

		Label nameSurname = createNameSurnameLable(closeImg);
		leftPanel.addChild(nameSurname);

		Img photo = createPhotoImg();
		leftPanel.addChild(photo);

		SectionStack sectionStack = createSectionStack();

		SectionStackSection section1 = new SectionStackSection(
				"Загальна інформація");
		section1.setExpanded(true);
		section1.setCanCollapse(true);
		section1.addItem(createGeneralInfoDetailViewer());
		sectionStack.addSection(section1);

		SectionStackSection section2 = new SectionStackSection(
				"Відвідані турніри");
		section2.setExpanded(false);
		section2.setCanCollapse(true);
		section2.addItem(createTournamentsDetailViewer());
		sectionStack.addSection(section2);

		addMember(sectionStack);

	}

	private SectionStack createSectionStack() {
		SectionStack sectionStack = new SectionStack();
		sectionStack.setHeight100();
		sectionStack.setWidth("*");
		sectionStack.setVisibilityMode(VisibilityMode.MUTEX);
		sectionStack.setAnimateAcceleration(AnimationAcceleration.SMOOTH_END);
		sectionStack.setAnimateSections(true);
		sectionStack.setOverflow(Overflow.HIDDEN);
		return sectionStack;
	}

	private Img createPhotoImg() {
		// Img photo = new Img("photos/"
		// + player.getAttribute(PlayerItem.PHOTO_URL));
		photo = new Img();
		// photo.setSrc("photos/" + player.getAttribute(PlayerItem.PHOTO_URL));
		photo.setHeight100();
		photo.setWidth100();
		photo.setPosition(Positioning.ABSOLUTE);
		photo.moveTo(0, 0);
		photo.setZIndex(1);
		photo.setBackgroundColor("black");
		return photo;
	}

	private Img createCloseFormImg() {
		final Img closeImg = new Img("img/icon_close.png");
		closeImg.setHeight(16);
		closeImg.setWidth(16);
		closeImg.setZIndex(3);
		closeImg.setPosition(Positioning.ABSOLUTE);
		closeImg.moveTo((int) (PlayerCanvas.APP_WIDTH * 0.4 - 26), 10);
		closeImg.setOpacity(50);
		closeImg.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				PlayerInfoLayout.this.hide();
			}
		});
		closeImg.addMouseOverHandler(new MouseOverHandler() {

			@Override
			public void onMouseOver(MouseOverEvent event) {
				closeImg.setOpacity(100);
			}
		});
		closeImg.addMouseOutHandler(new MouseOutHandler() {

			@Override
			public void onMouseOut(MouseOutEvent event) {
				closeImg.setOpacity(50);
			}
		});
		return closeImg;
	}

	private Label createNameSurnameLable(final Img closeImg) {
		// Label nameSurname = new Label(player.getAttribute(PlayerItem.NAME)
		// + " " + player.getAttribute(PlayerItem.SURNAME));
		nameSurname = new Label();
		// nameSurname.setContents(player.getAttribute(PlayerItem.NAME) + " "
		// + player.getAttribute(PlayerItem.SURNAME));
		nameSurname.setWidth100();
		nameSurname.setHeight(35);
		nameSurname.setStyleName("player_header");
		nameSurname.setAlign(Alignment.LEFT);
		nameSurname.setValign(VerticalAlignment.CENTER);
		nameSurname.setBackgroundImage("img/p.png");
		nameSurname.setBackgroundRepeat(BkgndRepeat.REPEAT);
		nameSurname.setPosition(Positioning.ABSOLUTE);
		nameSurname.moveTo(0, 0);
		nameSurname.setZIndex(2);
		nameSurname.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				onHideLayout();
			}

		});
		nameSurname.addMouseOverHandler(new MouseOverHandler() {

			@Override
			public void onMouseOver(MouseOverEvent event) {
				closeImg.setOpacity(100);
			}
		});
		nameSurname.addMouseOutHandler(new MouseOutHandler() {

			@Override
			public void onMouseOut(MouseOutEvent event) {
				closeImg.setOpacity(50);
			}
		});
		return nameSurname;
	}

	protected void onHideLayout() {
		hide();
	}

	private DetailViewer createDetailViewer() {
		DetailViewer detailViewer = new DetailViewer();
		detailViewer.setWidth100();
		detailViewer.setHeight100();
		detailViewer.setMargin(8);
		detailViewer.setOverflow(Overflow.AUTO);
		detailViewer.setBackgroundColor("transparent");
		detailViewer.setDataSource(datasource);
		return detailViewer;
	}

	private void setCriteriaAndFetchData(DetailViewer detailViewer,
			PlayerRecord playerRecord) {
		Criteria criteria = new Criteria();
		criteria.addCriteria(PlayerItem.ID,
				playerRecord.getAttribute(PlayerItem.ID));
		detailViewer.fetchData(criteria);
	}

	private DetailViewer createGeneralInfoDetailViewer() {
		generalDetailViewer = createDetailViewer();

		// setCriteriaAndFetchData(generalDetailViewer, player);

		DetailViewerField nativeCity = new DetailViewerField(
				PlayerItem.NATIVE_CITY);

		DetailViewerField playsFrom = new DetailViewerField(
				PlayerItem.PLAYS_FROM);
		playsFrom.setDetailFormatter(new DetailFormatter() {

			@Override
			public String format(Object value, Record record,
					DetailViewerField field) {
				return formatDate("MMMMM yyyy", record, PlayerItem.PLAYS_FROM);
			}

		});

		DetailViewerField birthday = new DetailViewerField(PlayerItem.BIRTHDAY);
		birthday.setDetailFormatter(new DetailFormatter() {

			@Override
			public String format(Object value, Record record,
					DetailViewerField field) {
				return formatDate("dd MMMMM yyyy", record, PlayerItem.BIRTHDAY);
			}
		});

		generalDetailViewer.setFields(nativeCity, playsFrom, birthday);

		return generalDetailViewer;
	}

	private DetailViewer createTournamentsDetailViewer() {
		tournamentsDetailViewer = createDetailViewer();

		// setCriteriaAndFetchData(tournamentsDetailViewer);

		// setTournamentFields(tournamentsDetailViewer, player);

		return tournamentsDetailViewer;
	}

	private void setTournamentFields(DetailViewer detailViewer,
			PlayerRecord playerRecord) {
		Record tournamentsPerYear = playerRecord
				.getAttributeAsRecord(PlayerItem.TOURNAMENTS);
		String[] attributes = tournamentsPerYear.getAttributes();
		List<Integer> years = new ArrayList<Integer>();
		for (String attr : attributes) {
			try {
				Integer iYear = Integer.valueOf(attr);
				years.add(iYear);
			} catch (NumberFormatException e) {

			}
		}

		List<DetailViewerField> fields = new LinkedList<DetailViewerField>();
		for (Integer year : years) {
			DetailViewerField field = new DetailViewerField(year.toString(),
					year.toString());

			final String tournamentsString = concatTournaments(
					tournamentsPerYear, year);

			field.setDetailFormatter(new DetailFormatter() {

				@Override
				public String format(Object value, Record record,
						DetailViewerField field) {
					return tournamentsString;
				}
			});
			fields.add(field);
		}

		if (fields.isEmpty()) {
			Date today = new Date();
			@SuppressWarnings("deprecation")
			DetailViewerField noTournaments = new DetailViewerField(
					String.valueOf(today.getYear() + 1900));
			noTournaments.setDetailFormatter(new DetailFormatter() {

				@Override
				public String format(Object value, Record record,
						DetailViewerField field) {
					return NO_TOURNAMENTS_YET;
				}
			});
			fields.add(noTournaments);
		}

		detailViewer.setFields(fields.toArray(new DetailViewerField[0]));

	}

	private String concatTournaments(Record tournamentsPerYear, Integer year) {
		String sumString = "";
		Record[] tournaments = tournamentsPerYear
				.getAttributeAsRecordArray(year.toString());
		for (int i = 0; i < tournaments.length; i++) {
			sumString += tournaments[i].getAttribute(TournamentItem.TITLE);
			if (i < tournaments.length - 1) {
				sumString += ", ";
			}
		}

		return sumString;
	}

	private String formatDate(String patern, Record record, String field) {
		SimpleDateFormat df = new SimpleDateFormat(patern);
		df.setLocale(new UkDateLocale());
		Date playsFrom = record.getAttributeAsDate(field);
		return df.format(playsFrom);
	}
}
